#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
剑网3装备数据MCP服务器配置文件

包含服务器配置、API配置、缓存配置等所有配置项
"""

import os
from dataclasses import dataclass, field
from typing import Dict, List


@dataclass
class ServerConfig:
    """服务器配置类"""
    # 基础服务器配置
    host: str = "0.0.0.0"
    port: int = 8000
    reload: bool = True
    access_log: bool = True
    log_level: str = "info"
    
    # 应用信息
    title: str = "剑网3装备数据MCP服务器"
    description: str = "基于FastAPI和MCP协议的高性能游戏数据查询服务，支持装备、套装、饰品数据查询"
    version: str = "1.2.0"
    
    # MCP配置
    mcp_name: str = "JX3 Equipment API MCP Server"
    mcp_description: str = "剑网3装备数据查询MCP服务器，为AI模型提供游戏装备数据查询功能"
    
    # API配置
    jx3box_base_url: str = "https://node.jx3box.com"
    request_timeout: float = 30.0
    max_retries: int = 3
    
    # 缓存配置
    enable_cache: bool = True
    cache_ttl: int = 300  # 5分钟默认缓存时间
    cache_size: int = 1000  # 最大缓存项目数


@dataclass
class ApiEndpoints:
    """API端点配置类"""
    # 装备查询端点
    equipment_search: str = "/equip/{equipment_type}"
    equipment_set: str = "/equip/set/{set_id}"
    equipment_detail: str = "/equip/{tab_type}/{equipment_id}"
    
    # 门派映射（剑网3所有门派）
    school_mapping: Dict[str, str] = field(default_factory=lambda: {
        "七秀": "七秀",
        "天策": "天策", 
        "纯阳": "纯阳",
        "万花": "万花",
        "藏剑": "藏剑",
        "丐帮": "丐帮",
        "明教": "明教",
        "苍云": "苍云",
        "长歌": "长歌",
        "霸刀": "霸刀",
        "蓬莱": "蓬莱",
        "凌雪": "凌雪",
        "衍天": "衍天",
        "药宗": "药宗",
        "刀宗": "刀宗",
        "万灵": "万灵",
        "相知": "相知",
        "段氏": "段氏",
        "牙郎": "牙郎"
    })
    
    # 装备类型映射
    equipment_types: Dict[str, str] = field(default_factory=lambda: {
        "weapon": "武器",
        "armor": "装备", 
        "trinket": "饰品"
    })
    
    # PV类型映射
    pv_types: Dict[int, str] = field(default_factory=lambda: {
        1: "PVE",
        2: "PVP", 
        3: "PVX"
    })
    
    # 心法类型映射
    duty_types: Dict[int, str] = field(default_factory=lambda: {
        1: "内功",
        2: "外功",
        3: "坦克",
        4: "奶妈"
    })


@dataclass
class ResponseConfig:
    """响应配置类"""
    # 分页配置
    default_page_size: int = 10
    max_page_size: int = 100
    
    # 响应格式配置
    include_timestamp: bool = True
    include_request_id: bool = False
    
    # 数据过滤配置
    filter_empty_fields: bool = False
    max_response_size: int = 10 * 1024 * 1024  # 10MB


@dataclass 
class CacheConfig:
    """缓存配置类"""
    # LRU缓存配置
    max_size: int = 1000
    default_ttl: int = 300  # 5分钟
    
    # 不同类型数据的TTL配置
    equipment_search_ttl: int = 300    # 装备搜索 5分钟
    equipment_set_ttl: int = 600       # 套装信息 10分钟
    equipment_detail_ttl: int = 1200   # 装备详情 20分钟
    school_summary_ttl: int = 600      # 门派汇总 10分钟
    popular_equipment_ttl: int = 900   # 热门装备 15分钟
    
    # 缓存清理配置
    cleanup_interval: int = 60  # 清理间隔 1分钟
    
    # 缓存键前缀
    key_prefix: str = "jx3_mcp:"


# 创建配置实例
server_config = ServerConfig()
api_endpoints = ApiEndpoints()
response_config = ResponseConfig()
cache_config = CacheConfig()


def load_config_from_env():
    """从环境变量加载配置"""
    # 服务器配置
    server_config.host = os.getenv("MCP_HOST", server_config.host)
    server_config.port = int(os.getenv("MCP_PORT", str(server_config.port)))
    server_config.reload = os.getenv("MCP_RELOAD", "true").lower() == "true"
    server_config.log_level = os.getenv("LOG_LEVEL", server_config.log_level)
    
    # API配置
    server_config.request_timeout = float(os.getenv("API_TIMEOUT", str(server_config.request_timeout)))
    server_config.max_retries = int(os.getenv("API_MAX_RETRIES", str(server_config.max_retries)))
    
    # 缓存配置
    server_config.enable_cache = os.getenv("ENABLE_CACHE", "true").lower() == "true"
    server_config.cache_ttl = int(os.getenv("CACHE_TTL", str(server_config.cache_ttl)))
    server_config.cache_size = int(os.getenv("CACHE_SIZE", str(server_config.cache_size)))
    
    # 响应配置
    response_config.default_page_size = int(os.getenv("DEFAULT_PAGE_SIZE", str(response_config.default_page_size)))
    response_config.max_page_size = int(os.getenv("MAX_PAGE_SIZE", str(response_config.max_page_size)))


def validate_config():
    """验证配置有效性"""
    errors = []
    
    # 验证端口号
    if not (1 <= server_config.port <= 65535):
        errors.append(f"无效的端口号: {server_config.port}")
    
    # 验证超时时间
    if server_config.request_timeout <= 0:
        errors.append(f"无效的请求超时时间: {server_config.request_timeout}")
    
    # 验证缓存配置
    if server_config.cache_size <= 0:
        errors.append(f"无效的缓存大小: {server_config.cache_size}")
    
    if server_config.cache_ttl <= 0:
        errors.append(f"无效的缓存时间: {server_config.cache_ttl}")
    
    # 验证分页配置
    if response_config.default_page_size <= 0:
        errors.append(f"无效的默认分页大小: {response_config.default_page_size}")
    
    if response_config.max_page_size <= response_config.default_page_size:
        errors.append(f"最大分页大小必须大于默认分页大小")
    
    if errors:
        raise ValueError("配置验证失败:\n" + "\n".join(f"- {error}" for error in errors))


def get_config_summary() -> Dict[str, any]:
    """获取配置摘要"""
    return {
        "server": {
            "host": server_config.host,
            "port": server_config.port,
            "version": server_config.version,
            "cache_enabled": server_config.enable_cache
        },
        "api": {
            "base_url": server_config.jx3box_base_url,
            "timeout": server_config.request_timeout,
            "max_retries": server_config.max_retries
        },
        "cache": {
            "ttl": server_config.cache_ttl,
            "size": server_config.cache_size
        },
        "response": {
            "default_page_size": response_config.default_page_size,
            "max_page_size": response_config.max_page_size
        }
    }


# 初始化时加载环境变量配置
load_config_from_env()

# 验证配置
try:
    validate_config()
except ValueError as e:
    print(f"⚠️ 配置警告: {e}")

# 打印配置摘要（调试用）
if __name__ == "__main__":
    import json
    print("📋 配置摘要:")
    print(json.dumps(get_config_summary(), indent=2, ensure_ascii=False)) 